/**
 * 用户认证状态管理 Store
 */

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { AuthService, type User } from '@/services/auth.service';
import { auth } from '@/services/api';

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref<User | null>(null);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // Getters
  const isAuthenticated = computed(() => !!user.value);
  const userId = computed(() => user.value?.id);

  // Actions
  /**
   * 用户注册
   */
  async function register(data: {
    username: string;
    email: string;
    password: string;
    nickname: string;
  }) {
    try {
      isLoading.value = true;
      error.value = null;
      
      const response = await AuthService.register(data);
      
      // 保存token
      auth.setToken(response.access_token);
      user.value = response.user;
      
      return response;
    } catch (e: any) {
      error.value = e.message || '注册失败';
      throw e;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 用户登录
   */
  async function login(usernameOrEmail: string, password: string) {
    try {
      isLoading.value = true;
      error.value = null;
      
      const response = await AuthService.login({ usernameOrEmail, password });
      
      // 保存token
      auth.setToken(response.access_token);
      user.value = response.user;
      
      return response;
    } catch (e: any) {
      error.value = e.message || '登录失败';
      throw e;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 用户登出
   */
  function logout() {
    user.value = null;
    auth.clearToken();
  }

  /**
   * 获取用户信息
   */
  async function fetchUser() {
    try {
      isLoading.value = true;
      const userInfo = await AuthService.getProfile();
      user.value = userInfo;
    } catch (e: any) {
      error.value = e.message || '获取用户信息失败';
      logout();
      throw e;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 更新用户信息
   */
  async function updateProfile(data: { nickname?: string; avatar_url?: string }) {
    try {
      isLoading.value = true;
      error.value = null;
      
      const updatedUser = await AuthService.updateProfile(data);
      user.value = updatedUser;
      
      return updatedUser;
    } catch (e: any) {
      error.value = e.message || '更新用户信息失败';
      throw e;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 检查用户名是否存在
   */
  async function checkUsername(username: string): Promise<boolean> {
    return AuthService.checkUsername(username);
  }

  /**
   * 检查邮箱是否存在
   */
  async function checkEmail(email: string): Promise<boolean> {
    return AuthService.checkEmail(email);
  }

  /**
   * 清除错误
   */
  function clearError() {
    error.value = null;
  }

  /**
   * 初始化认证状态
   */
  async function initAuth() {
    const token = auth.getToken();
    if (token) {
      try {
        await fetchUser();
      } catch (e) {
        // Token无效，清除认证状态
        logout();
      }
    }
  }

  return {
    // State
    user,
    isLoading,
    error,
    // Getters
    isAuthenticated,
    userId,
    // Actions
    register,
    login,
    logout,
    fetchUser,
    updateProfile,
    checkUsername,
    checkEmail,
    clearError,
    initAuth,
  };
});
